package org.jcms.uitils;

import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * 购物车操作cookie的工具类
 * 方法说明：add 加数据
 *     delete 删除数据
 *     setOrAdd 修改或增加
 *     set 修改
 *     gets 将cookie中的数据以JSONArray 对象的形式返回
 *     getCookieCount 返回cookie中记录的条数
 *     dropCookie 删除cookie
 *     
 * @author pgh
 * 
 */
public class CookieUtil {
	/**
	 * 这个方法用于向cookie中增加数据，如果原本已经存在该记录，则在此基础在增，如果cookie中本没有这个数据，则增加进去。这个方法局限性很大。
	 * 
	 * @param cookieName
	 *            要获取cookie的名称
	 * @param cookiePath
	 *            cookie的保存路径
	 * @param jsonId
	 *            当原cookie中名称为jsonid的值与传入的参数的名称为jsonid的值相等时表示同一对象。
	 * @param jsonNumber
	 *            这个表示要增加的数据的名称
	 * @param json传入要增加的数据
	 * @param savetime设置cookie的保存时间
	 * @param request
	 * @param response
	 * @return 当传入的参数json为空时，返回-1。传入的数据json非空时返回操作后cookie中记录的条数。
	 * @throws JSONException
	 */
	public static int add(String cookieName, String cookiePath, String jsonId,
			String jsonNumber, List<Map<String, String>> json, int savetime,
			HttpServletRequest request, HttpServletResponse response)
			throws JSONException {
		if (json == null || json.size() == 0) {
			return -1;
		}
		JSONArray oldJsonArray = gets(cookieName, cookiePath, savetime,
				request, response);
		JSONArray newJsonArray = new JSONArray(json);
		for (int j = 0; oldJsonArray != null && j < newJsonArray.length(); j++) {
			String newJsonId = newJsonArray.getJSONObject(j).getString(jsonId);
			for (int i = 0; i < oldJsonArray.length(); i++) {
				String oldJsonId = oldJsonArray.getJSONObject(i).getString(
						jsonId);
				if (oldJsonId.equals(newJsonId)) {
					int oldNumber = Integer.parseInt(oldJsonArray
							.getJSONObject(i).getString(jsonNumber));
					int addNumber = Integer.parseInt(newJsonArray
							.getJSONObject(j).getString(jsonNumber));
					oldJsonArray.getJSONObject(i).put(jsonNumber,
							String.valueOf(oldNumber + addNumber));
					break;
				} else if (i == oldJsonArray.length() - 1) {
					oldJsonArray.put(oldJsonArray.length(),
							newJsonArray.getJSONObject(j));
					break;
				}
			}
		}
		Cookie cookie = new Cookie(cookieName, "");
		cookie.setMaxAge(savetime);
		cookie.setPath(cookiePath);
		if (oldJsonArray != null) {
			cookie.setValue(oldJsonArray.toString());
			response.addCookie(cookie);
			return oldJsonArray.length();
		} else {
			cookie.setValue(newJsonArray.toString());
			response.addCookie(cookie);
			return newJsonArray.length();
		}

	}

	/**
	 * 删除cookie中的某个值
	 * 
	 * @param cookieName
	 * @param jsonId
	 * @param savetime
	 * @param request
	 * @param response
	 * @throws JSONException
	 */
	public static void delete(String cookieName, String cookiePath,
			String jsonId, String jsonIdValue, int savetime,
			HttpServletRequest request, HttpServletResponse response)
			throws JSONException {
		JSONArray oldJsonArray = gets(cookieName, cookiePath, savetime,
				request, response);
		JSONArray newJsonArray = new JSONArray();
		for (int i = 0; oldJsonArray != null && i < oldJsonArray.length(); i++) {
			if (jsonIdValue.equals(oldJsonArray.getJSONObject(i).getString(
					jsonId))) {
				continue;
			}
			newJsonArray.put(newJsonArray.length(),
					oldJsonArray.getJSONObject(i));
		}
		Cookie cookie = new Cookie(cookieName, newJsonArray.toString());
		cookie.setMaxAge(savetime);
		cookie.setPath(cookiePath);
		response.addCookie(cookie);
	}

	/**
	 * 这个方法是修改cookie中的某些值，如果cookie中本没有这个值则将传入的值保存到cookie中，如果本来有值，则修改成传入的值
	 * 
	 * @param cookieName
	 * @param cookiePath
	 *            如果浏览器没有带来cookie(原本没有)，则此时要设置cookie的有效路径
	 * @param jsonId
	 *            根据这个参数确定cookie中哪一个对象的值需要修改
	 * @param json
	 *            传入要修改的值的集合
	 * @param savetime
	 * @param request
	 * @param response
	 * @throws JSONException
	 */
	public static void setOrAdd(String cookieName, String cookiePath,
			String jsonId, List<Map<String, String>> json, int savetime,
			HttpServletRequest request, HttpServletResponse response)
			throws JSONException {
		if (json == null || json.size() == 0) {
			return;
		}
		JSONArray oldJsonArray = gets(cookieName, cookiePath, savetime,
				request, response);
		JSONArray newJsonArray = new JSONArray(json);
		for (int j = 0; oldJsonArray != null && j < newJsonArray.length(); j++) {
			String newJsonId = newJsonArray.getJSONObject(j).getString(jsonId);
			for (int i = 0; i < oldJsonArray.length(); i++) {
				String oldJsonId = oldJsonArray.getJSONObject(i).getString(
						jsonId);
				if (oldJsonId.equals(newJsonId)) {
					oldJsonArray.put(i, newJsonArray.getJSONObject(j));
					break;
				} else if (i == oldJsonArray.length() - 1) {
					oldJsonArray.put(oldJsonArray.length(),
							newJsonArray.getJSONObject(j));
					break;
				}
			}
		}
		Cookie cookie = new Cookie(cookieName, null);
		cookie.setMaxAge(savetime);
		cookie.setPath(cookiePath);
		if (oldJsonArray != null) {
			cookie.setValue(oldJsonArray.toString());
		} else {
			cookie.setValue(newJsonArray.toString());
		}
		response.addCookie(cookie);

	}

	/**
	 * 修改cookie中值，如果没有要修改的值则不处理（即不将该值保存到cookie中）
	 * 
	 * @param cookieName
	 * @param jsonId
	 * @param json
	 * @param savetime
	 * @param request
	 * @param response
	 * @throws JSONException
	 */
	public static void set(String cookieName, String cookiePath, String jsonId,
			List<Map<String, String>> json, int savetime,
			HttpServletRequest request, HttpServletResponse response)
			throws JSONException {
		JSONArray oldJsonArray = gets(cookieName, cookiePath, savetime,
				request, response);
		if (json == null || json.size() == 0 || oldJsonArray == null
				|| oldJsonArray.length() == 0) {
			return;
		}
		JSONArray newJsonArray = new JSONArray(json);
		for (int j = 0; j < newJsonArray.length(); j++) {
			String newJsonId = newJsonArray.getJSONObject(j).getString(jsonId);
			for (int i = 0; i < oldJsonArray.length(); i++) {
				String oldJsonId = oldJsonArray.getJSONObject(i).getString(
						jsonId);
				if (oldJsonId.equals(newJsonId)) {
					oldJsonArray.put(i, newJsonArray.getJSONObject(j));
					break;
				}
			}
		}
		Cookie cookie = new Cookie(cookieName, oldJsonArray.toString());
		cookie.setMaxAge(savetime);
		cookie.setPath(cookiePath);
		response.addCookie(cookie);
	}

	/**
	 * 获取指定名称的cookie的值并将其转化成JSONArray对象返回，如果指定cookie不存在，返回null.
	 * 
	 * @param cookieName
	 * @param savetime
	 * @param request
	 * @param response
	 * @return
	 * @throws JSONException
	 *             异常不能try最好要抛出，这样外界调用者才知道操作出错了。
	 */
	public static JSONArray gets(String cookieName, String cookiePath,
			int savetime, HttpServletRequest request,
			HttpServletResponse response) throws JSONException {
		Cookie cookie = getCookie(cookieName, request);
		if (cookie != null) {
			cookie.setMaxAge(savetime);
			cookie.setPath(cookiePath);
			response.addCookie(cookie);
			String value = cookie.getValue();
			if (value != null && !"".equals(value)) {
				return new JSONArray(value);
			} else {
				return null;
			}
		}
		return null;
	}

	/**
	 * 获取cookie中保存的字符串
	 * 
	 * @param savetime
	 *            回写cookie时，该值为设置cookie保存的时间（单位秒）
	 * @param cookieName
	 * @param request
	 * @param response
	 * @return
	 */
	public static String getString(String cookieName, String cookiePath,
			int savetime, HttpServletRequest request,
			HttpServletResponse response) {
		Cookie cookie = getCookie(cookieName, request);
		if (cookie != null) {
			cookie.setMaxAge(savetime);
			cookie.setPath(cookiePath);
			response.addCookie(cookie);
			return cookie.getValue();
		}
		return null;
	}
	/**
	 * 删除指定的cookie,此时只要该cookie设置的有效路径和要删除的cookie的有效路径一样，就能成功删除指定的cookie.
	 * 
	 * @param cookieName
	 * @param cookiePath
	 * @param request
	 * @param response
	 */
	public static void dropCookie(String cookieName, String cookiePath,
			HttpServletRequest request, HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieName, "");
		cookie.setPath(cookiePath);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	public static int getCookieCount(String cookieName, String cookiePath,int savetime,
			HttpServletRequest request, HttpServletResponse response) throws JSONException {
		JSONArray jsonArray = gets(cookieName, cookiePath, savetime, request, response);
		if(jsonArray==null){
			return 0;
		}
		return jsonArray.length();
	}

	/**
	 * 获取cookie，在没有取得指定名称的cookie的情况下返回null.
	 * 
	 * @param request
	 * @param cookieName
	 * @return
	 */
	private static Cookie getCookie(String cookieName,
			HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			if (cookies[i].getName().equals(cookieName)) {
				return cookies[i];
			}
		}
		return null;
	}
}
